package com.yonyou.pmclouds.uspace.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonyou.iuap.tenant.sdk.TenantCenter;
import com.yonyou.pmclouds.basecom.conf.DeployTypeConfiguration;
import com.yonyou.pmclouds.basecom.conf.USpaceProperties;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.util.HttpTookit;
import com.yonyou.pmclouds.uspace.util.USpaceUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.io.IOException;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/mobile/uspace")
public class SSOLoginController {

    @Autowired
    private USpaceProperties uspaceProperties;

    // 特定的key（请求需要的）
    public static final String TOKEN_KEY = "token";
    public static final String TIMESTAMP_KEY = "timestamp";
    public static final String V_KEY = "v";
    public static final String AGENT_ID_KEY = "agent_id";
    public static final String FROMCHANNEL = "fromChannel";

    private ObjectMapper jsonMapper = new ObjectMapper();

    @RequestMapping("/ssoLogin")
    public Object ssoLogin(String userCode) throws BusinessException {

//        String successResult = "{\"code\":0,\"level\":0,\"msg\":\"成功\",\"data\":{\"instance_id\":\"211407\",\"qz_id\":\"16425\",\"tenant_id\":\"x61tnmfx\",\"member_id\":\"3280375\",\"user_id\":\"261218\",\"yht_userid\":\"5b34bcf1-ca22-459c-9998-0b28d2564446\",\"name\":\"杨昆\",\"avatar\":\"\",\"duty\":\"\",\"dept_id\":\"0\",\"sex\":\"保密\",\"is_admin\":0,\"dept_name\":\"\",\"mobile\":\"13301058035\",\"email\":\"cysync_sesess_6415505835877449728@upesn.com\",\"time\":1542180921,\"expireIn\":1542180981,\"staff_no\":\"\",\"yht_token\":\"43ba79e1-cb61-448c-a6bc-edd00d0999d8\",\"status\":1}}";
//        String errorResult = "{\"code\":30005,\"level\":0,\"msg\":\"身份验证失败，请重新登录\"}";

        String result = queryLoginUserInfo(userCode);
        log.error("友空间单点登录结果："+result);

        Map<String,Object> resultMap = new HashMap<String,Object>();
        try {
            resultMap = jsonMapper.readValue(result,Map.class);
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new BusinessException(e.getMessage(),e);
        }

        if( resultMap.get("code")!= null && (int)resultMap.get("code")!=0)
            throw new BusinessException("友空间单点登录出错，错误编码："+resultMap.get("code")+",错误信息："+resultMap.get("msg"));

        Map<String,Object> userMap = resultMap.get("data") == null ? new HashMap<String, Object>():(Map<String,Object>)resultMap.get("data");

        String userId = (String)userMap.get("yht_userid");
        String access_token = (String)userMap.get("yht_token");
        String userName = (String)userMap.get("name");
        String tenantId = (String)userMap.get("tenant_id");

//        if(!checkUserCanLogin(userId,tenantId))
//            throw new BusinessException("用户在该租户下没有应用权限");

        Map<String,Object> loginResultMap = new HashMap<String,Object>();
        loginResultMap.put("userid",userId);
        loginResultMap.put("username",userName);
        Map<String,Object> dataMap = new HashMap<String,Object>();
        dataMap.put("access_token",access_token);
        log.error("从友空间处获得的token："+access_token);
        loginResultMap.put("data",dataMap);

        try {
            log.error("友空间单点最终返回值："+jsonMapper.writeValueAsString(loginResultMap));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return loginResultMap;
    }


    private boolean checkUserCanLogin(String userId,String tenantId) throws BusinessException{
        List<Map> canTenantList = getPMCTenant(userId);

        if(canTenantList == null || canTenantList.size() == 0)
            throw new BusinessException("用户没有可登录的租户");

        boolean checkValue = false;

        for (Map map :
                canTenantList) {
            if (StringUtils.equals(tenantId,(String)map.get("tenantId"))) {
                checkValue = true;
                break;
            }
        }
        return checkValue;
    }

    private List<Map> getPMCTenant(String userId) throws BusinessException {
        // 判断用户是否有包含PMC的数据中心
        String canLoginResult = TenantCenter.getCanLoginTenants(userId, DeployTypeConfiguration.getSysId());

        if (StringUtils.isEmpty(canLoginResult))
            throw new BusinessException("获取用户可登录本应用的企业中心出错：友户通服务异常");
        Map tenantMap = null;
        try {
            tenantMap = jsonMapper.readValue(canLoginResult, Map.class);
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        if (Integer.valueOf(0).equals(tenantMap.get("status"))) {
            log.error("获取用户可登录本应用的数据中心错误，错误信息为：" + tenantMap.get("msg"));
            throw new BusinessException("获取用户应用权限信息失败");
        }

        List<Map> canTenantList = (ArrayList<Map>) tenantMap.get("tenants");
        return canTenantList;
    }


    private String queryLoginUserInfo(String userCode) throws BusinessException{
        // 请求参数准备
        Map<String, String> parameters = new HashMap<>();
        parameters.put(TIMESTAMP_KEY, String.valueOf(System.currentTimeMillis()));
        parameters.put(V_KEY, uspaceProperties.getV());
        parameters.put(AGENT_ID_KEY, uspaceProperties.getAgentId());
        parameters.put(FROMCHANNEL, "uspaceApp");
        parameters.put(TOKEN_KEY, uspaceProperties.getToken());

        String url = USpaceUtil.buildGetUrl( uspaceProperties.getSsologin().getUri()+"/"+ userCode,uspaceProperties,parameters);

        return HttpTookit.doGet(url,null);
    }



}
